<?php
/**
 * 网络请求模块
 * User: 毛文科
 * Date: 2019/3/8 0008
 * Time: 16:14
 */
namespace shortmessage\src;
class Curl
{
    private $url = '';
    private $type = '';
    private $data = '';
    private $fanhui = 1;
    private $rulit = '';
    //设置请求地址
    public function setUrl($url=''){
        if($url){
            $this->url = $url;
        }
        return $this;
    }
    //设置请求类型
    public function setType($type=''){
        if ($type){
            $this->type = $type;
        }
        return $this;
    }
    //设置请求数据
    public function setData($data=null){
        if($data){
            $this->data = $data;
        }
        return $this;
    }
    //设置返回类型
    public function setFanhui($fanhui=1){
        $this->fanhui = $fanhui;
        return $this;
    }
    //发送数据
    public function fasong($url='',$fanhui='',$post=0,$data=''){
        if($url){
            $this->url = $url;
        }
        if($fanhui){
            $this->fanhui = $fanhui;
        }
        if($post==1){
            $this->type = 'post';
        }
        if($data){
            $this->data = $data;
        }
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$this->url);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,$this->fanhui);
        if($this->type=='post'||$this->type=='POST'){
            curl_setopt($curl,CURLOPT_POST,1);
        }
        if($this->data){
            curl_setopt($curl,CURLOPT_POSTFIELDS,$this->data);
        }
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($curl);
        curl_close($curl);
        $this->rulit = $result;
        return $this;
    }

    public static function staticfasong($url,$data=[],$type='json'){
        $obj = new Curl();
        if($data){
            $data = json_encode($data);
            $obj->fasong($url,$obj->fanhui,1,$data);
        }else{
            $obj->fasong($url,$obj->fanhui);
        }
        if($type=='json'){
            return $obj->jsonToArray()->get();
        }elseif ($type=='xml'){
            return $obj->xml()->get();
        }
    }

    /**设置返回值
     * @param $xml
     * @return $this
     */
    public function setRulit($xml){
        $this->rulit = $xml;
        return $this;
    }
    //解析xml数据
    public function xml(){
        $xml = $this->rulit;
        $xml = simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA);
        $data  = (array)$xml;
        $this->rulit = $data;
        return $this;
    }
    //获取返回数据
    public function get(){
        return $this->rulit;
    }

    /**解析xml
     * @param $data
     * @return array
     */
    public function xmlToArray($data){
        $data = simplexml_load_string($data,'SimpleXMLElement',LIBXML_NOCDATA);
        return (array)$data;
    }

    /**解析json格式
     * @return $this
     */
    public function jsonToArray(){
        $this->rulit = json_decode($this->rulit,true);
        return $this;
    }
}